package labox.innovation.loginserver.socket.clientpackets;

import labox.innovation.loginserver.LoginController;
import labox.innovation.loginserver.socket.serverpackets.RegisterOk.RegistFailReason;
import labox.innovation.config.Config;

/**
 * 客户端注册账号接收包
 * 
 * @author Frank
 * 
 */
public class ClientRegisterPacket extends LoginClientPacket {

	/**
	 * 用户名
	 */
	private String _userName;

	/**
	 * 密码
	 */
	private String _passWord;

	/**
	 * Sdk
	 */
	private byte _sdk;

	/**
	 * 渠道ID
	 */
	private String _channelID;

	/**
	 * 手机平台信息
	 */
	private String _clientInfo;

	/**
	 * 协议版本号
	 */
	private int _clientVersion;

	/**
	 * 返回协议版本号的检查情况
	 * 
	 * @param clientVersion
	 * @return
	 */
	private boolean checkClientVersion(int clientVersion) {//临时解决方案
		return true;
//		return ((clientVersion >= Config.MIN_PROTOCOL_REVISION) && (clientVersion <= Config.MAX_PROTOCOL_REVISION));
	}

	@Override
	protected void readImpl() {
		_userName = readString();
		_passWord = readString();
		_sdk = readByte();
		_channelID = readString();
		_clientInfo = readString();
		_clientVersion = readInt();
	}

	@Override
	public void run() {
		
		LoginController lc=LoginController.getInstance();
		//进行必要的简单检查
		if (_userName == null || !lc.isValidName(_userName)) {
			getClient().close(RegistFailReason.REASON_USER_OR_PASS_WRONG.getRegisterOk());
			return;
		}
		if (_passWord == null || !lc.isValidPassword(_passWord)) {
			getClient().close(RegistFailReason.REASON_USER_OR_PASS_WRONG.getRegisterOk());
			return;
		}
		if (_channelID == null || _channelID.length() == 0) {
			getClient().close(RegistFailReason.REASON_SYSTEM_ERROR.getRegisterOk());
			return;
		}
		if (_clientInfo == null)
			return;

		if (!checkClientVersion(_clientVersion)) { //-- 版本检查
			getClient().close(RegistFailReason.REASON_VERSION_ERROR.getRegisterOk());
		} else {
			
			if(!Config.CREATEACCOUNTS){
				getClient().close(RegistFailReason.REASON_SYSTEM_ERROR.getRegisterOk());
				return;
			}
				
			int iReg =lc.registerAccountSyn(_userName, _passWord, getClient().getInetAddress().getHostAddress(), _sdk, _channelID, _clientInfo, _clientVersion);
			if (iReg == 0) { //-- 判断账户存在
				getClient().close(RegistFailReason.REASON_ACCOUNT_REGISTED.getRegisterOk()); //-- 返回错误码0,表示注册失败
			} else { //-- 账户不存在则执行注册操作
				if (iReg == 1) {
					getClient().close(RegistFailReason.REASON_OK.getRegisterOk());
				} else {
					getClient().close(RegistFailReason.REASON_SYSTEM_ERROR.getRegisterOk());
				}
			}
		}
	}
}
